package vip.aster.generator.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import vip.aster.common.utils.PageInfo;
import vip.aster.common.utils.ResultInfo;
import vip.aster.generator.config.DataSourceConfig;
import vip.aster.generator.entity.GenDataSource;
import vip.aster.generator.entity.GenTable;
import vip.aster.generator.query.Query;
import vip.aster.generator.service.GenDataSourceService;
import vip.aster.generator.utils.DbUtils;
import vip.aster.generator.utils.GenUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 数据源管理
 *
 * @author Aster
 * @since 2024/2/26 16:32
 */
@Slf4j
@RestController
@RequestMapping("/gen/datasource")
@AllArgsConstructor
@Tag(name = "数据源管理")
public class DataSourceController {
    private final GenDataSourceService datasourceService;

    @GetMapping("/page")
    public ResultInfo<PageInfo<GenDataSource>> page(Query query) {
        PageInfo<GenDataSource> page = datasourceService.page(query);

        return ResultInfo.success(page);
    }

    @GetMapping("/list")
    public ResultInfo<List<GenDataSource>> list() {
        List<GenDataSource> list = datasourceService.getList();

        return ResultInfo.success(list);
    }

    @GetMapping("/info/{id}")
    public ResultInfo<GenDataSource> get(@PathVariable("id") String id) {
        GenDataSource data = datasourceService.getById(id);

        return ResultInfo.success(data);
    }

    @GetMapping("/test/{id}")
    public ResultInfo<String> test(@PathVariable("id") String id) {
        try {
            GenDataSource entity = datasourceService.getById(id);

            DbUtils.getConnection(new DataSourceConfig(entity));
            return ResultInfo.success("连接成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultInfo.failed("连接失败，请检查配置信息");
        }
    }

    @PostMapping("/save")
    public ResultInfo<String> save(@RequestBody GenDataSource entity) {
        datasourceService.saveDataSource(entity);
        return ResultInfo.success();
    }

    @PostMapping("/delete")
    public ResultInfo<String> delete(@RequestBody List<String> ids) {
        datasourceService.removeBatchByIds(ids);

        return ResultInfo.success();
    }

    /**
     * 根据数据源ID，获取全部数据表
     *
     * @param id 数据源ID
     */
    @GetMapping("/table/list/{id}")
    public ResultInfo<List<GenTable>> tableList(@PathVariable("id") String id) {
        try {
            // 获取数据源
            DataSourceConfig datasource = datasourceService.get(id);
            // 根据数据源，获取全部数据表
            List<GenTable> tableList = GenUtils.getTableList(datasource);

            return ResultInfo.success(tableList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultInfo.failed("数据源配置错误，请检查数据源配置！");
        }
    }
}
